import 'package:auto_route/auto_route.dart';
import 'package:convergence_media/features/config/logger/logger.dart';
import 'package:convergence_media/features/user/controller/login_controller.dart';
import 'package:convergence_media/features/user/controller/timer_controller.dart';
import 'package:convergence_media/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

@RoutePage<bool>()
class LoginScreen extends ConsumerWidget {
  const LoginScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeData = Theme.of(context);

    return SafeArea(
      child: Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: [
            Positioned(
              width: 1.sw,
              height: 306.r,
              child: ColoredBox(
                color: themeData.primaryColor,
                child: const SizedBox.shrink(),
              ),
            ),
            Positioned(
              left: 39.r,
              top: 202.r,
              width: 332.r,
              height: 85.r,
              child: DecoratedBox(
                decoration: BoxDecoration(
                  color: Colors.white30,
                  borderRadius: BorderRadius.circular(20.r),
                ),
              ),
            ),
            Positioned(
              left: 157.r,
              top: 81.r,
              width: 100.r,
              height: 100.r,
              child: const _PersonIconWidget(),
            ),
            Positioned(
              left: 21.r,
              top: 215.r,
              width: 369.r,
              height: 462.r,
              child: const _LoginWidget(),
            ),
          ],
        ),
      ),
    );
  }
}

class _PersonIconWidget extends StatelessWidget {
  const _PersonIconWidget();

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100.r,
      height: 100.r,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(50.r),
        border: Border.all(color: Colors.white),
        color: Colors.white,
      ),
      alignment: Alignment.center,
      padding: EdgeInsets.all(
        1.r,
      ),
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50.r),
          border: Border.all(
            color: Theme.of(context).primaryColor,
            width: 3.r,
          ),
        ),
        child: const CircleAvatar(
          radius: 50,
          backgroundColor: Colors.white,
          foregroundImage: NetworkImage(
            'https://img.js.design/assets/img/64f85140c53eb65dd2fc7583.png#ee469d315f8605404eb98c26caca1e39',
          ),
        ),
      ),
    );
  }
}

class _LoginWidget extends HookConsumerWidget {
  const _LoginWidget();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final phoneTextEditingController = useTextEditingController();
    final codeTextEditingController = useTextEditingController();
    final usePhoneValueListenable =
        useValueListenable(phoneTextEditingController);
    final useCodeValueListenable =
        useValueListenable(codeTextEditingController);

    useEffect(
      () {
        phoneTextEditingController.text = usePhoneValueListenable.text;
        codeTextEditingController.text = useCodeValueListenable.text;
        return null;
      },
      [phoneTextEditingController, codeTextEditingController],
    );

    ref.listen(
      loginControllerProvider,
      (_, state) {
        if (!state.isLoading && state.hasError) {
          logger.e(state.error, stackTrace: state.stackTrace);
          showDialog<void>(
            context: context,
            builder: (context) => AlertDialog.adaptive(
              content: Text(state.error.toString()),
            ),
          );
        }
      },
    );

    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 23.r,
        vertical: 23.r,
      ),
      decoration: BoxDecoration(
        color: const Color(0xfffafafa),
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: Column(
        children: [
          SizedBox(
            height: 36.r,
          ),
          _PhoneTextField(
            phoneTextEditingController: phoneTextEditingController,
          ),
          SizedBox(
            height: 10.r,
          ),
          if (phoneTextEditingController.text.length == 11)
            _VerificationCodeTextField(
              codeTextEditingController: codeTextEditingController,
              phoneTextEditingController: phoneTextEditingController,
            ).animate().fadeIn(),

          SizedBox(
            height: 60.r,
          ),
          _LoginButton(
            codeTextEditingController: codeTextEditingController,
            phoneTextEditingController: phoneTextEditingController,
          ),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.end,
          //   children: [
          //     const Text('没有账号？'),
          //     TextButton(
          //       onPressed: () {},
          //       child: const Text(
          //         '去登录 >',
          //         style: TextStyle(color: Colors.red),
          //       ),
          //     ),
          //   ],
          // ),
          // const SizedBox(
          //   height: 32,
          // ),
          // const Row(
          //   children: [
          //     Expanded(
          //       child: Divider(
          //         thickness: 1,
          //         indent: 8,
          //         endIndent: 8,
          //       ),
          //     ),
          //     Text('第三方登录'),
          //     Expanded(
          //       child: Divider(
          //         thickness: 1,
          //         indent: 8,
          //         endIndent: 8,
          //       ),
          //     ),
          //   ],
          // ),
          // const Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     Spacer(),
          //     Icon(Icons.ios_share),
          //     Icon(Icons.ios_share),
          //     Icon(Icons.ios_share),
          //     Icon(Icons.ios_share),
          //     Spacer(),
          //   ],
          // ),
        ],
      ),
    );
  }
}

class _PhoneTextField extends StatelessWidget {
  const _PhoneTextField({
    required TextEditingController phoneTextEditingController,
  }) : _phoneTextEditingController = phoneTextEditingController;

  final TextEditingController _phoneTextEditingController;

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _phoneTextEditingController,
      decoration: InputDecoration(
        prefixIconConstraints: BoxConstraints.tight(
          Size(
            64.r,
            20.r,
          ),
        ),
        prefixIcon: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: 8.r,
          ),
          child: Assets.images.login.phone.image(),
        ),
        label: Text(
          '请输入手机号码',
          style: TextStyle(fontSize: 16.sp),
        ),
      ),
    );
  }
}

class _VerificationCodeTextField extends HookConsumerWidget {
  const _VerificationCodeTextField({
    required TextEditingController phoneTextEditingController,
    required TextEditingController codeTextEditingController,
  })  : _phoneTextEditingController = phoneTextEditingController,
        _codeTextEditingController = codeTextEditingController;

  final TextEditingController _codeTextEditingController;
  final TextEditingController _phoneTextEditingController;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return TextField(
      controller: _codeTextEditingController,
      decoration: InputDecoration(
        prefixIconConstraints: BoxConstraints.tight(
          Size(
            64.r,
            20.r,
          ),
        ),
        prefixIcon: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: 8.r,
          ),
          child: Assets.images.login.smscode.image(),
        ),
        label: Text(
          '请输入验证码',
          style: TextStyle(fontSize: 16.sp),
        ),
        suffixIconConstraints: BoxConstraints.tight(
          Size(
            102.r,
            30.r,
          ),
        ),
        suffixIcon: ref.watch(loginControllerProvider).map(
              data: (data) => _GetVerificationCodeButton(
                phoneTextEditingController: _phoneTextEditingController,
              ),
              error: (AsyncError<LoginState> error) {
                return _GetVerificationCodeButton(
                  phoneTextEditingController: _phoneTextEditingController,
                );
              },
              loading: (loading) {
                return const Center(
                  child: CircularProgressIndicator.adaptive(),
                );
              },
            ),
      ),
    );
  }
}

/// {@template _get_verification_code_button}
/// 获取验证码按钮
/// {@endtemplate}
class _GetVerificationCodeButton extends HookConsumerWidget {
  /// {@macro _get_verification_code_button}
  const _GetVerificationCodeButton({
    required TextEditingController phoneTextEditingController,
  }) : _phoneTextEditingController = phoneTextEditingController;

  final TextEditingController _phoneTextEditingController;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeData = Theme.of(context);

    return InkWell(
      onTap: () => ref
          .read(loginControllerProvider.notifier)
          .sendSms(_phoneTextEditingController.text),
      child: Center(
        child: Container(
          width: 84.r,
          height: 24.r,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(90.r),
            color: themeData.primaryColor,
          ),
          alignment: Alignment.center,
          child: Text(
            '获取验证码',
            style: TextStyle(fontSize: 11.sp, color: Colors.white),
          ),
        ),
      ),
    );
  }
}

/// 登录按钮
class _LoginButton extends ConsumerWidget {
  const _LoginButton({
    required TextEditingController phoneTextEditingController,
    required TextEditingController codeTextEditingController,
  })  : _codeTextEditingController = codeTextEditingController,
        _phoneTextEditingController = phoneTextEditingController;

  final TextEditingController _phoneTextEditingController;
  final TextEditingController _codeTextEditingController;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeData = Theme.of(context);

    return InkWell(
      onTap: () async {
        final router = AutoRouter.of(context);
        await ref.read(loginControllerProvider.notifier).login(
              _phoneTextEditingController.text,
              _codeTextEditingController.text,
            );
        await router.pop<bool>(true);
      },
      child: Container(
        width: 281.r,
        height: 46.r,
        decoration: BoxDecoration(
          color: themeData.primaryColor,
          borderRadius: BorderRadius.circular(90.r),
        ),
        alignment: Alignment.center,
        child: Text(
          '登录并注册',
          style: TextStyle(fontSize: 18.sp, color: Colors.white),
        ),
      ),
    );
  }
}
